import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/auth',
    name: 'Auth',
    // component: () => import('@/views/auth/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/auth/LoginView.vue'),
        meta: { title: '登录' }
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/auth/RegisterView.vue'),
        meta: { title: '注册' }
      },
      {
        path: 'forgot-password',
        name: 'ForgotPassword',
        component: () => import('@/views/auth/ForgotPasswordView.vue'),
        meta: { title: '忘记密码' }
      }
    ]
  },
  // 分享访问路由 (无需登录)
  {
    path: '/s/:shareCode',
    name: 'ShareAccess',
    component: () => import('@/views/share/ShareAccess.vue'),
    meta: {
      requiresAuth: false,
      title: '文件分享'
    }
  },
  // 支付结果页面 (独立布局)
  {
    path: '/pay-result',
    name: 'PaymentResult',
    component: () => import('@/views/PayResult.vue'),
    meta: { 
      requiresAuth: false,
      title: '支付结果' 
    }
  },
  // VIP支付页面 (Electron专用)
  {
    path: '/vip-payment',
    name: 'VipPayment',
    component: () => import('@/views/VipPayment.vue'),
    meta: { 
      requiresAuth: true,
      title: 'VIP支付' 
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/dashboard/DashboardLayoutWrapper.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/dashboard/HomeView.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'files',
        name: 'Files',
        component: () => import('@/views/files/FilesView.vue'),
        meta: { title: '我的文件' }
      },
      {
        path: 'trash',
        name: 'Trash',
        component: () => import('@/views/trash/TrashView.vue'),
        meta: { title: '回收站' }
      },
      {
        path: 'transfer',
        name: 'Transfer',
        component: () => import('@/views/transfer/TransferList.vue'),
        meta: { title: '传输列表' }
      },
      {
        path: 'storage-repair',
        name: 'StorageRepair',
        component: () => import('@/views/dashboard/StorageRepair.vue'),
        meta: { title: '存储修复' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/dashboard/ProfileView.vue'),
        meta: { title: '个人资料' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/settings/SettingsView.vue'),
        meta: { title: '设置' }
      },
      {
        path: 'electron-settings',
        name: 'ElectronSettings',
        component: () => import('@/views/electron/ElectronSettingsView.vue'),
        meta: { title: 'Electron设置' }
      },
      {
        path: 'shared',
        name: 'Shared',
        component: () => import('@/views/share/ShareManage.vue'),
        meta: { title: '分享管理' }
      },
      {
        path: 'favorites',
        name: 'Favorites',
        component: () => import('@/views/favorites/FavoritesView.vue'),
        meta: { title: '收藏夹' }
      },

      {
        path: 'ai-chat',
        name: 'AIChat',
        component: () => import('@/views/dashboard/AIChatView.vue'),
        meta: { title: 'AI助手' }
      },
      {
        path: 'contacts',
        name: 'Contacts',
        component: () => import('@/views/contacts/ContactsView.vue'),
        meta: { title: '联系人' }
      },
      {
        path: 'team',
        name: 'TeamManagement',
        component: () => import('@/views/team/TeamManagement.vue'),
        meta: { title: '团队管理' }
      },
      {
        path: 'team/:id',
        name: 'TeamDetail',
        component: () => import('@/views/team/TeamDetail.vue'),
        meta: { title: 'team.teamDetail' }
      },
      {
        path: 'team/:id/settings',
        name: 'TeamSettings',
        component: () => import('@/views/team/TeamSettings.vue'),
        meta: { title: 'team.teamSettings' }
      },
      {
        path: 'admin/team-approval',
        name: 'TeamApproval',
        component: () => import('@/views/admin/TeamApproval.vue'),
        meta: { title: '团队审核', requireAdmin: true }
      },
      {
        path: 'test/rabbitmq',
        name: 'RabbitMQTest',
        component: () => import('@/views/test/RabbitMQTest.vue'),
        meta: { title: 'RabbitMQ压测', requireAdmin: true }
      },
      {
        path: 'work-reports',
        component: () => import('@/views/work-reports/WorkReportsLayout.vue'),
        meta: { title: 'AI工作报告' },
        children: [
          {
            path: '',
            name: 'WorkReports',
            redirect: { name: 'WorkRecords' }
          },
          {
            path: 'records',
            name: 'WorkRecords',
            component: () => import('@/views/work-reports/RecordView.vue'),
            meta: { title: '工作记录' }
          },
          {
            path: 'generate',
            name: 'ReportGenerate',
            component: () => import('@/views/work-reports/GenerateView.vue'),
            meta: { title: '报告生成' }
          },
          {
            path: 'manage',
            name: 'ReportManage',
            component: () => import('@/views/work-reports/ManageView.vue'),
            meta: { title: '报告管理' }
          },
          {
            path: 'detail/:id',
            name: 'ReportDetail',
            component: () => import('@/views/work-reports/ReportDetailView.vue'),
            meta: { title: '报告详情' }
          },
          {
            path: 'statistics',
            name: 'WorkStatistics',
            component: () => import('@/views/work-reports/StatisticsView.vue'),
            meta: { title: '数据统计' }
          },
          {
            path: 'settings',
            name: 'WorkReportSettings',
            component: () => import('@/views/work-reports/SettingsView.vue'),
            meta: { title: '配置设置' }
          }
        ]
      },
      {
        path: 'vip-center',
        name: 'VipCenter',
        component: () => import('@/views/VipCenter.vue'),
        meta: { title: 'VIP会员中心' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题 - 这里暂时跳过，让TitleBar组件处理
  // if (to.meta?.title) {
  //   document.title = `${to.meta.title} - RickPan`
  // }

  const authStore = useAuthStore()

  // 如果是登录页面但已经登录，跳转到首页
  if (to.path === '/auth/login' && authStore.isAuthenticated) {
    next('/dashboard')
    return
  }

  // 检查认证
  if (to.meta?.requiresAuth) {
    // 如果没有token，跳转到登录页
    if (!authStore.token) {
      next('/auth/login')
      return
    }

    // 如果有token但没有用户信息，尝试获取用户信息
    if (!authStore.user) {
      try {
        await authStore.getCurrentUser()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 获取用户信息失败，清除token并跳转到登录页
        localStorage.removeItem('token')
        authStore.token = ''
        authStore.user = null
        next('/auth/login')
        return
      }
    }
  }

  // 检查管理员权限
  if (to.meta?.requiresAdmin) {
    if (!authStore.isAdmin) {
      console.warn('访问被拒绝：需要管理员权限', to.path)
      // 跳转到首页或显示无权限页面
      next('/dashboard')
      return
    }
  }

  next()
})

export default router
